package httpclient

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var (
	URL            = "url"
	METHOD         = "method"
	COOKIE         = "cookie"
	PRINT          = "print"
	CONTENT_TYPE   = "Content-Type"
	ADD_HEADER     = "add-header"
	ACCEPT_CHARSET = "Accept-Charset"
)

// HttpClient 用来存放请求的相关的信息的结构体
type HttpClient struct {
	path        string            // 请求地址
	method      string            // 请求方式
	contentType string            // 请求类型
	cookie      string            // cookie
	proxy       string            // 代理
	charset     string            // 字符编码
	addHeader   map[string]string // 添加的请求头信息
	printf      string            // 请求内容返回
}

func NewHttpClient() *HttpClient {
	return &HttpClient{}
}

// Url 设置请求根地址
func (h *HttpClient) Url(url string) *HttpClient {
	h.path = url
	return h
}

// Method 设置请求方法
func (h *HttpClient) Method(method string) *HttpClient {

	h.method = method
	return h
}

func (h *HttpClient) Cookie(cookie string) *HttpClient {
	return h
}

// AddHeader 增加请求头信息
func (h *HttpClient) AddHeader(header string) *HttpClient {
	if len(header) > 0 {
		h.addHeader = make(map[string]string)
		headers := strings.Split(header, ";")
		for i := 0; i < len(headers); i++ {
			values := strings.Split(headers[i], "=")
			if len(values) == 2 {
				h.addHeader[values[0]] = values[1]
			}
		}
	}
	return h
}

// Charset 设置字符编码
func (h *HttpClient) Charset(chartSet string) *HttpClient {
	if h.addHeader == nil {
		h.addHeader = make(map[string]string)
	}
	h.addHeader[ACCEPT_CHARSET] = chartSet
	return h
}

// ContentType 请求类型
func (h *HttpClient) ContentType(types string) *HttpClient {
	if h.addHeader == nil {
		h.addHeader = make(map[string]string)
	}
	h.addHeader[CONTENT_TYPE] = types
	return h
}

// Printf 输出数据
func (h *HttpClient) Printf(out string) *HttpClient {
	h.printf = out
	return h
}

// Build 发送请求
func (h *HttpClient) Build() error {
	request, err := http.NewRequest(strings.ToUpper(h.method), h.path, nil)
	if err != nil {
		return err
	}
	if len(h.addHeader) > 0 {
		for k, v := range h.addHeader {
			request.Header.Set(k, v)
		}
	}
	response, err := (&http.Client{}).Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	data, _ := ioutil.ReadAll(response.Body)
	switch h.printf {
	case "console":
		fmt.Printf(string(data))
	case "file":
		err = ioutil.WriteFile(time.Now().Format("20060102150405")+".out", data, 0644)
		if err != nil {
			return err
		}
	case "status":
		fmt.Println("请求状态：", response.Status)
	}
	return nil
}
